import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select, TreeSelect, Popover, Tooltip,
} from 'antd';
import BuildModalTitle from '@/components/BuildModalTitle';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';


import debounce from 'lodash/debounce';
import ReactDataGrid from 'react-data-grid';
import request from '@/utils/request';
import { download, formateObjToParamStr } from '@/utils/utils';
import config from '@/config/config';
import AreaMap from "@/components/AreaMap";
const FormItem = Form.Item;
const { confirm } = Modal;
const Option = Select.Option;
const InputGroup = Input.Group;
const ButtonGroup = Button.Group;
@connect(({ daily_payment_reports, loading, global }) => ({
  daily_payment_reports,
  global,
  loading: loading.models.daily_payment_reports,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      data: [],
      remark:'',
      invoicingData:[]
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      daily_payment_reports: { pageLoaded, scrollData },
    } = this.props;

    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        daily_payment_reports: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'daily_payment_reports/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'daily_payment_reports/changeLoaded',
          });
          dispatch({
            type: 'daily_payment_reports/changeTableY',
          });
        },
      });

    }
    const that = this;
    request(`/all_regions`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          data: response.data.data,
        });
      }
    });
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
    // document.addEventListener('keyup', this.keyupFunc);

  }

  keyupFunc = (e) => {
    if (e.keyCode === 13) {
      this.searchFunc();
    }
  };
  searchFunc = () => {
    const that = this;
    const { form, daily_payment_reports: { searchParams } } = that.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;

      this.handleSearch({
        ...fieldsValue,
        start_date: moment(fieldsValue.start_date).format('YYYY-MM-DD'),
        end_date: moment(fieldsValue.end_date).format('YYYY-MM-DD'),

      });

    });
  };
  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'daily_payment_reports/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    // this.changeTableY();
    dispatch({
      type: 'daily_payment_reports/changeTableY',
    });
  };
  changeTableY = () => {
    this.setState({
      tableY: document.querySelector('.bottom-analysis').getBoundingClientRect().top -
        document.querySelector('.custom-small-table').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    // document.removeEventListener('keyup', this.keyupFunc);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  findChildFunc = (cb) => {
    this.findChildLocation = cb;
  };
  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    const {
      daily_payment_reports: { searchInputType, searchInputText },
    } = this.props;
    dispatch({
      type: 'daily_payment_reports/fetch',
      payload: {
        ...values,
        [searchInputType]: searchInputText,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const data = this.state.data;
    const { dispatch } = this.props;
    const {
      daily_payment_reports: { searchParams, searchInputType, searchInputText },
    } = this.props;
    const form=this.props.form
    const getFieldDecorator=form.getFieldDecorator
    return (
      <Form layout="inline" className="search-form">
        <AreaMap form={form} searchParams={searchParams} getFieldDecorator={getFieldDecorator}/>
        <FormItem label={'开始日期'}>
          {getFieldDecorator('start_date', {
            initialValue: moment(searchParams.start_date),
          })(
            <DatePicker
              style={{ width: '120px' }}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>
        <FormItem label={'结束日期'}>
          {getFieldDecorator('end_date', {
            initialValue: moment(searchParams.end_date),
          })(
            <DatePicker
              style={{ width: '120px' }}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />,
          )}
        </FormItem>

        <FormItem label="类型">
          {getFieldDecorator('payment_type', {
            initialValue: searchParams.payment_type,
          })(
            <Select style={{ width: '100px' }}>
              {
                [{ id: '', value: '全部' },
                  { id: '1', value: '柜台缴费' },
                  { id: '2', value: '公众号缴费' },
                 ].map((item, index) => {
                  return <Option key={index} value={item.id}>{item.value}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              this.searchFunc();
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
        </FormItem>
        <FormItem>
          <ButtonGroup>
            <Button type="primary" onClick={()=>{
              const {
                daily_payment_reports: { searchParams },
              } = this.props;
              this.handleSearch({
                payment_type:searchParams.payment_type,
                start_date: moment(searchParams.start_date).subtract(1,'month').format('YYYY-MM-01'),
                end_date:moment(searchParams.start_date).subtract(1,'month').endOf('month').format('YYYY-MM-DD'),
              });
            }}>
              <Icon type="left" />
              前一个月
            </Button>
            <Button type="primary"  onClick={()=>{
              const {
                daily_payment_reports: { searchParams },
              } = this.props;
              this.handleSearch({
                payment_type:searchParams.payment_type,
                start_date: moment(searchParams.start_date).add(1,'month').format('YYYY-MM-01'),
                end_date:moment(searchParams.start_date).add(1,'month').endOf('month').format('YYYY-MM-DD'),
              });
            }}>
              后一个月
              <Icon type="right" />
            </Button>
          </ButtonGroup>
        </FormItem>

      </Form>
    );
  }
  keyPress=(e)=>{
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press')
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        this.searchFunc()
      });
    }
  }

  handleFormReset = () => {
    const { form } = this.props;
    const { dispatch } = this.props;
    const that=this
    form.resetFields();
    dispatch({
      type: 'daily_payment_reports/changeOneProperty',
      payload: {
        searchInputType: 'mobile',
        searchInputText: '',
        searchParams: {
          company_ids:sessionStorage.getItem('company_sign'),
          company_id:'',
          start_date:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+'01' , "YYYY-MM-DD").format("YYYY-MM-DD"),
          end_date:moment(new Date()).format('YYYY-MM-DD'),
          payment_type: '',
        },
      },
      callback() {
        that.handleSearch({
          company_ids:sessionStorage.getItem('company_sign'),
          company_id:'',
          start_date: moment(new Date().getFullYear() + '-' + (parseInt(new Date().getMonth()) + 1) + '-' + '01', 'YYYY-MM-DD').format('YYYY-MM-DD'),
          end_date: moment(new Date()).format('YYYY-MM-DD'),
          payment_type: '',
        });
      },
    });
  };
  handleExportPayment = () => {
    const {
      daily_payment_reports: { searchParams },
    } = this.props;
    console.log('searchParams', searchParams);
    download(`${config.prefix}/daily_payment_report_files?Authorization=Bearer ${sessionStorage.getItem('token')}&order_direction=desc&${formateObjToParamStr(searchParams)}`);

  };
  render() {
    const that = this;
    const {
      daily_payment_reports: { data, loading, tableY, meta, searchParams, selectedRowKeys, summary },
      global: { gridTableW },
    } = this.props;
    const defaultColumnProperties = {
      resizable: true,
    };
    const username=sessionStorage.getItem('username')
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        formatter: (event) => {
          const {
            daily_payment_reports: { meta },
          } = this.props;
          return <p className={'index'}>{(event.value + 1)}</p>;
        },
      },
      {
        name: '缴费日期',
        width: 150,
        key: 'date',
      },
      {
        name: '缴费总笔数',
        width: 150,
        key: 'total_count',
        formatter: (event) => {
          return <span style={{color:'rgb(0,0,0)',fontWeight:'bold'}}>{event.value}</span>
        }
      },
      {
        name: '缴费总金额',
        width: 150,
        key: 'total_amount',
        formatter: (event) => {
          return <span style={{color:'rgb(38, 181, 26)',fontWeight:'bold'}}>{event.value}</span>
        }
      },
      {
        name: '已开票金额',
        width: 150,
        key: 'invoiced_amount',
        formatter: (event) => {
          return <span style={{color:'rgb(0, 104, 201)',fontWeight:'bold'}}>{event.value}</span>
        }
      }, {
        name: '未开票金额',
        width: 150,
        key: 'uninvoiced_amount',
        formatter: (event) => {
          return <span style={{color:'rgb(224, 0, 0)',fontWeight:'bold'}}>{event.value}</span>
        }
      },
    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>缴费记录</span>
      </div>
      <div className="table-page">
        <div className="table-info">
          <div className="table-info-item  animated fadeInLeft">
            <p>缴费总笔数</p>
            <h4>{summary.total_count}</h4>
          </div>
          <div className="table-info-item  animated fadeInLeft">
            <p style={{ color: '#26b51a' }}>缴费总金额</p>
            <h4 style={{ color: '#26b51a' }}> {summary.total_amount}</h4>
          </div>
          <div className="table-info-item  animated fadeInLeft">
            <p style={{ color: '#0068c9' }}>已开票金额</p>
            <h4 style={{ color: '#0068c9' }}>{summary.invoiced_amount}</h4>
          </div>
          <div className="table-info-item  animated fadeInLeft">
            <p style={{ color: '#e00000' }}>未开票金额 </p>
            <h4 style={{ color: '#e00000' }}>{summary.uninvoiced_amount}</h4>
          </div>
          <div size="large" className="table-info-right-item  animated fadeInRight">
          {
            find(this.permissions, { name: 'revenue_report_export' }) &&
            <Tooltip title={'请先查询一次再导出'}>
              <Button
                className={'btn-green'}
                type="primary"
                icon="export"
                onClick={this.handleExportPayment}
              >导出缴费记录
              </Button>
            </Tooltip>
          }

          </div>
        </div>
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                if (!String(row)) {
                  return;
                }
                this.props.dispatch({
                  type: 'daily_payment_reports/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
    </div>;
  }
}

export default BasicList;
